<template>
	<view class="page chat-box">
		<nav-header custom-nav @on-show-more="onShowMore" :title="title">
			<template v-slot:left>
				<view class="left">
					<slot name="left">
						<uni-icons class="back" type="back" size="28" @tap="onNavBack()"></uni-icons>
					</slot>
				</view>
			</template>
		</nav-header>
		<!-- #ifdef APP-PLUS -->
		<view v-if="showNotice" style="margin-top: 40rpx;">
			<topNotice :message="topMessage" v-if="showNotice" :title="topTitle"></topNotice>
		</view>
		<!-- #endif -->
		<view class="top_daohang">
			<view class="top_daohang_font" @click="openLive()"
				v-if="chat.type == 'GROUP' && (chat.originalData.groupType !=0)">直播</view>
			<view style="background-color: #F5F5F5;">
				<BoardPanel v-model="id" width="188" show show-modal show-list
					v-if="chat.type == 'GROUP' && (chat.originalData.groupType !=0)" />
			</view>
			<view class="top_daohang_font" @click="openVideo()"
				v-if="chat.type == 'GROUP' && (chat.originalData.groupType !=0)">小视频</view>
		</view>
		<view class="chat-msg" @click="switchChatTabBox('none', true)">
			<view class="notice" v-if="notice" @tap="openModal"> <!-- 公告 -->
				<up-modal :show="modalShow" :closeOnClickOverlay="true" showCancelButton @cancel="onRead"
					@confirm="goDetail" cancel-text="已读" confirmText="查看详情" :title="noticeTitle"
					:content='notice.content'></up-modal>
				<!-- 点击后的弹出窗 -->
			</view>
			<scroll-view class="scroll-box" :scroll-y="true" :upper-threshold="200"
				:style="{ height: scrollViewHeight + 'px' }" @scrolltoupper="onScrollToTop" :scroll-top="scrollTop"
				show-scrollbar=true :scroll-into-view="'chat-item-' + scrollMsgIdx">
				<view id="scroll-view-content">
					<view v-if="chat" v-for="(msgInfo, idx) in messageList" :key="idx">
						<chat-message-item v-if="idx >= showMinIdx" :headImage="headImage(msgInfo)"
							@call="onRtCall(msgInfo)" :showName="showName(msgInfo)" @recall="onRecallMessage"
							@copy="onCopyMessage(msgInfo)" @favorite="onFavorite" @delete="onDeleteMessage"
							@longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile"
							:id="'chat-item-' + idx" :msgInfo="msgInfo" :groupMembers="groupMembers"
							:url-params="{ sourceType: sourceType, fromThis: chat.type != 'GROUP' }" :group="group">
						</chat-message-item>
					</view>
					<view v-if="fixNotice.length > 0" class="send-bar-fixed" style="height: 100rpx;">
					</view>
					<view v-else class="send-bar-fixed" style="height: 50rpx;"></view>
				</view>
			</scroll-view>
		</view>
		<view class="send-panel">
			<!-- 固定公告 -->
			<view v-if="fixNotice.length > 0" class="fixed-notice">
				<view v-for="(item,index) in fixNotice" :key="item.id" :class="item.isRead?'fixNotice1':'fixNotice'"
					@tap="openFix(item.id)">
					<up-modal :show="showFixId === item.id" showCancelButton @cancel="fixRead(item.id,index)"
						@confirm="fixDetail(item.id,index)" cancel-text="已读" confirmText="查看详情" :title="noticeTitle"
						:content='item.content'></up-modal> <!-- 点击后的弹出窗 -->
					{{ item.content }}
					<view class="red-dot" v-if="!item.isRead"></view>
				</view>
			</view>

			<!-- @用户时选择成员 -->
			<chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers"
				@complete="onAtComplete"></chat-at-box>
			<view style="font-size: 25rpx;color: #3b82f6;padding: 0 10rpx;" v-if="atUserIds.length > 0"
				@tap.stop.native="atUserIds = []">
				清空
			</view>
			<view v-if="atUserIds.length > 0" class="chat-at-bar" @click="openAtBox()">
				<!-- <view class="iconfont icon-at">:&nbsp;</view> -->
				<scroll-view v-if="atUserIds.length > 0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
					<view class="chat-at-items">
						<view v-for="m in atUserItems" class="chat-at-item">
							<!-- <head-image :name="m.showNickName" :url="m.headImage" :size="40"></head-image> -->
							<!-- <text>@</text><text>{{m.showNickName}}</text> -->
							<up-tag :text="'@' + m.showNickName" size="mini" closable
								:show="atUserIds.includes(m.userId)"
								@click="atUserIds.splice(atUserIds.indexOf(m.userId))"
								@close="atUserIds.splice(atUserIds.indexOf(m.userId))"></up-tag>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="send-bar" :style="{ minHeight: containerHeight + 'px' }">
				<!-- <view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view> -->
				<view v-if="!showRecord" style="padding: 0 10rpx;" @click="onRecorderInput()">
					<svg-icon icon="audio" :width="48"></svg-icon>
				</view>
				<!-- <view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view> -->
				<view v-else style="padding: 0 10rpx;" @click="onKeyboardInput()">
					<svg-icon icon="keyboard" :width="48"></svg-icon>
				</view>
				<chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"
					@permissionRequestComplete="handlePermissionResult"></chat-record>
				<view v-else :class="['send-text', !inGroup && 'disabled']">
					<view class="not-in-group" v-if="!inGroup">
						您已退出群聊
					</view>
					<textarea :auto-height="true" class="send-text-area" :disabled="!inGroup" v-model="sendText"
						:show-confirm-bar="false" :placeholder="isReceipt ? '[回执消息]' : ''" :adjust-position="false"
						@confirm="sendTextMessage()" @keyboardheightchange="onKeyboardheightchange" @input="onTextInput"
						confirm-type="send" confirm-hold :hold-keyboard="true"></textarea>
				</view>
				<!-- <view v-if="chat && chat.type=='GROUP'" class="iconfont icon-at" @click="openAtBox()"></view> -->
				<!-- <view class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view> -->
				<view @click="onShowEmoChatTab()">
					<svg-icon icon="emoj" :width="48"></svg-icon>
				</view>
				<!-- <view v-if="sendText == ''" class="iconfont icon-add" @click="onShowToolsChatTab()"> -->
				<!-- </view> -->
				<view v-if="sendText == ''" @click="onShowToolsChatTab()">
					<svg-icon icon="add" :width="48"></svg-icon>
				</view>
				<button v-if="sendText != '' || atUserIds.length > 0" class="btn-send" type="primary"
					@tap.prevent="sendTextMessage()" size="mini">发送</button>
			</view>
			<!-- #ifndef APP-PLUS -->
			<view class="chat-tab-bar" v-show="chatTabBox != 'none' || (showKeyBoard && !isH5)"
				:style="showKeyBoard ? { height: `${keyboardHeight}px` } : ''">
			<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<view class="chat-tab-bar" v-if="chatTabBox != 'none' || (showKeyBoard && !isH5)"
					:style="showKeyBoard ? { height: `${keyboardHeight}px` } : ''">
				<!-- #endif -->
					<view v-if="chatTabBox == 'tools'" class="chat-tools">
						<view class="chat-tools-item" v-if="funcMap['ltym_xx']">
							<image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
								:onSuccess="onUploadImageSuccess" :onError="onUploadImageFail"
								@permissionRequestComplete="handlePermissionImage">
								<!-- <view class="tool-icon iconfont icon-picture"></view> -->
								<view class="tool-icons">
									<svg-icon icon="images-2" :width="64"></svg-icon>
								</view>
							</image-upload>
							<view class="tool-name">相册</view>
						</view>
						<view class="chat-tools-item" v-if="funcMap['ltym_px']">
							<image-upload sourceType="camera" :onBefore="onUploadImageBefore"
								:onSuccess="onUploadImageSuccess" :onError="onUploadImageFail"
								@permissionRequestComplete="handlePermissionPhoto">
								<!-- <view class="tool-icon iconfont icon-camera"></view> -->
								<view class="tool-icons1">
									<svg-icon icon="camera1" :width="64"></svg-icon>
								</view>
							</image-upload>
							<view class="tool-name">拍摄</view>
						</view>

						<view class="chat-tools-item" v-if="funcMap['ltym_wj']">
							<file-upload :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
								:onError="onUploadFileFail">
								<!-- <view class="tool-icon iconfont icon-folder"></view> -->
								<view class="tool-icons2">
									<svg-icon icon="folder-dots" :width="64"></svg-icon>
								</view>
							</file-upload>
							<view class="tool-name">文件</view>
						</view>

						<view class="chat-tools-item" @click="onRecorderInput()" v-if="funcMap['ltym_yyxx']">
							<!-- <view class="tool-icon iconfont icon-microphone"></view> -->
							<view class="tool-icons1">
								<svg-icon icon="voice_message" :width="64"></svg-icon>
							</view>
							<view class="tool-name">语音消息</view>
						</view>
						<view v-if="funcMap['ltym_hzxx'] && chat.type == 'GROUP'" class="chat-tools-item"
							@click="switchReceipt()">
							<!-- <view class="tool-icon iconfont icon-receipt" :class="isReceipt ? 'active' : ''"></view> -->
							<view class="tool-icons1">
								<svg-icon icon="massage" :width="64"></svg-icon>
							</view>
							<view class="tool-name">回执消息</view>
						</view>
						<!-- #ifndef MP-WEIXIN -->
						<!-- 音视频不支持小程序 -->
						<view v-if="funcMap['ltym_spth'] && chat.type == 'PRIVATE'" class="chat-tools-item"
							@click="onPriviteVideo()">
							<!-- <view class="tool-icon iconfont icon-video"></view> -->
							<view class="tool-icons1">
								<svg-icon icon="webcam" :width="64"></svg-icon>
							</view>
							<view class="tool-name">视频通话</view>
						</view>
						<view v-if="funcMap['ltym_yyth'] && chat.type == 'PRIVATE'" class="chat-tools-item"
							@click="onPriviteVoice()">
							<!-- <view class="tool-icon iconfont icon-call"></view> -->
							<view class="tool-icons3">
								<svg-icon icon="phone-call-outgoing" :width="64"></svg-icon>
							</view>
							<view class="tool-name">语音通话</view>
						</view>
						<view v-if="funcMap['ltym_yyth'] && chat.type == 'GROUP'" class="chat-tools-item"
							@click="onGroupVideo()">
							<!-- <view class="tool-icon iconfont icon-call"></view> -->
							<view class="tool-icons3">
								<svg-icon icon="phone-call-outgoing" :width="64"></svg-icon>
							</view>
							<view class="tool-name">语音通话</view>
						</view>
						<!-- #endif -->
					</view>
					<scroll-view v-if="chatTabBox === 'emo'" class="chat-emotion" scroll-y="true">
						<view class="emotion-item-list">
							<text class="emotion-item" v-for="(emoText, i) in $emo.emojiList" :key="i"
								@click="selectEmoji(emoText)" :title="emoText">{{ emoText }}</text>
						</view>
					</scroll-view>
					<view v-if="showKeyBoard"></view>
				</view>
			</view>
			<!-- 群语音通话时选择成员 -->
			<!-- #ifndef MP-WEIXIN -->
			<group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel"
				@complete="onInviteOk"></group-member-selector>
			<group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
			<!-- #endif -->
		</view>
</template>

<script>
	import {
		isNullOrEmpty
	} from '@/utils';
	import BoardPanel from '@/components/board-panel/board-panel.vue';
	// #ifdef APP-PLUS
	import topNotice from '@/components/topNotice/topNotice.vue'; // 引入自定义组件
	// #endif

	export default {
		components: {
			BoardPanel
		},
		data() {
			return {
				id: null,
				chat: {},
				chatIndex: null,
				sourceType: null,
				type: null,
				showNotice: null,
				scrollViewHeight: 100,
				scrollTop: 0,
				friend: {},
				group: {},
				groupMembers: [],
				sendText: "",
				isReceipt: false, // 是否回执消息027
				scrollMsgIdx: 0, // 滚动条定位为到哪条消息
				chatTabBox: 'none',
				showKeyBoard: false,
				showRecord: false,
				keyboardHeight: 0,
				atUserIds: [],
				notice: null,
				fixNotice: [],
				text1: "",
				needScrollToBottom: false, // 需要滚动到底部 
				showMinIdx: 0, // 下标小于showMinIdx的消息不显示，否则可能很卡
				reqQueue: [], // 请求队列x
				isSending: false, // 是否正在发送请求
				inGroup: true, // 是否还在群里
				modalShow: true, //公告弹窗
				showFixId: null, //显示弹窗的id
				noticeTitle: "公告内容",
				isH5: false, // h5键盘会强制推起页面，有些地方要区别对待
				videoSrc: 'https://vjs.zencdn.net/v/oceans.mp4',
				direction: 'all',
				containerHeight: 31,
				topTitle: "",
				topMessage: ""
			}
		},
		methods: {
			openLive() {
				uni.showToast({
					title: "开发中,敬请期待",
					icon: "none"
				})
			},
			openVideo() {
				uni.showToast({
					title: "开发中,敬请期待",
					icon: "none"
				})
			},
			// 处理权限请求结果
			handlePermissionResult(isGranted) {
				this.topTitle = "语音权限使用说明"
				this.topMessage = "用于进行语音沟通以及语音通话"
				this.showNotice = isGranted
			},
			handlePermissionImage(isGranted) {
				this.topTitle = "媒体权限使用说明"
				this.topMessage = "用于从设备相册中选择已有的媒体文件进行展示"
				this.showNotice = isGranted
			},
			handlePermissionPhoto(isGranted) {
				this.topTitle = "相机权限使用说明"
				this.topMessage = "用于相机拍摄照片进行图片的展示"
				this.showNotice = isGranted
			},
			onMovableChange(e) {
				// 处理移动事件，例如更新视频位置等
				// console.log('Movable view changed:', e);
			},
			onChange(e) {
				this.old.x = e.detail.x
				this.old.y = e.detail.y
			},
			GoChat() {
				uni.switchTab({
					url: "/pageSubOne/chat/chat"
				})
			},
			goDetail() {
				this.modalShow = false
				uni.navigateTo({
					url: "/pageSubOne/group/group-announce-detail?id=" + this.notice.id
				})
				this.loadGroupNotice(this.chat.targetId) //加载最新公告
			},
			onRead() {
				this.$http({
					url: `/group/readGroupNotice?noticeId=${this.notice.id}`,
					method: "POST",
				}).then(() => {
					this.loadGroupNotice(this.chat.targetId) //加载最新公告
					this.modalShow = false
				})
			},
			fixRead(id, i) {
				this.$http({
					url: `/group/readGroupNotice?noticeId=${id}`,
					method: "POST",
				}).then(() => {
					this.fixNotice[i].isRead = true
					// this.loadGroupNotice(this.chat.targetId) //加载最新公告
					this.showFixId = null
				})
			},
			fixDetail(id, i) {
				this.showFixId = null
				uni.navigateTo({
					url: "/pageSubOne/group/group-announce-detail?id=" + id
				})
				this.fixNotice[i].isRead = true
				// this.loadGroupNotice(this.chat.targetId) //加载最新公告
			},
			openModal() {
				this.modalShow = !this.modalShow
			},
			openFix(id) {
				this.showFixId = id
			},
			loadGroupNotice(id) {

				let data = {
					groupId: id
				}

				this.$http({
					url: `/group/findUnReadPopGroupNotice/${id}`,
					method: "GET"
				}).then((notice) => {
					console.log("notice", notice)
					if (notice && notice.id != null) {
						// 后期修改判断逻辑
						this.notice = notice
					}

				})

				this.$http({
					url: `/group/findGroupNotice?pageNum=1&pageSize=50`,
					method: 'POST',
					data: data
				}).then((notice) => {
					if (notice) {
						this.fixNotice = notice && notice.records && notice.records.filter(i => i.isFixedBox)
							.slice(0, 3) || []
					}
				})
			},
			// 滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					setTimeout(() => {
						uni.createSelectorQuery().in(this).select('#scroll-view-content')
							.boundingClientRect((res) => {
								uni.getSystemInfo({
									success: (v => {
										// // #ifdef MP-WEIXIN
										// const iniH = 135
										// // #endif
										// // #ifndef MP-WEIXIN
										// const iniH = 30
										// // #endif
										// this.scrollViewHeight = v.windowHeight - uni
										// 	.upx2px(150) -
										// 	// 固定公告
										// 	(this.fixNotice && this
										// 		.fixNotice.length > 0 && 24 || 0) -
										// 	// 工具bar
										// 	(this.chatTabBox == "none" ? iniH : 400) -
										// 	// 键盘高度
										// 	this.keyboardHeight
										// // scroll容器的高度
										// this.scrollTop = res.height - this
										// 	.scrollViewHeight

										// #ifdef MP-WEIXIN
										const iniH = 135;
										// #endif
										// #ifndef MP-WEIXIN
										const iniH = 30;
										// #endif
										const fixNoticeHeight = this.fixNotice && this
											.fixNotice.length > 0 ? 24 : 0;
										const chatTabBoxHeight = this.chatTabBox ==
											"none" ? iniH : 400;
										// #ifndef APP-PLUS
										const totalHeight = v.windowHeight - uni
											.upx2px(150) - fixNoticeHeight -
											chatTabBoxHeight - this.keyboardHeight;
										// #endif
										// #ifdef APP-PLUS
										const totalHeight = v.windowHeight - uni
											.upx2px(150) - fixNoticeHeight -
											chatTabBoxHeight - this.keyboardHeight -
											90;
										// #endif

										// #ifndef MP-WEIXIN
										if (this.chatTabBox == 'emo' || this
											.chatTabBox == 'tools') {
											this.scrollViewHeight = totalHeight + 100;
										} else {
											this.scrollViewHeight = totalHeight;
										}
										// #endif
										// #ifdef MP-WEIXIN
										this.scrollViewHeight = totalHeight;
										// #endif
										// #ifndef MP-WEIXIN
										this.scrollTop = res.height - totalHeight +
											this.scrollViewHeight
										// #endif
										// #ifdef MP-WEIXIN
										this.scrollTop = res.height - totalHeight
										// #endif
									})
								});
							}).exec()
					}, 100)
				})
			},

			onRecorderInput() {
				this.showRecord = true;
				this.switchChatTabBox('none', true);
				this.showKeyBoard = false
			},
			onKeyboardInput() {
				this.showRecord = false;
				this.switchChatTabBox('none', false);
			},
			onSendRecord(data) {
				let msgInfo = {
					content: JSON.stringify(data),
					type: this.$enums.MESSAGE_TYPE.AUDIO,
					receipt: this.isReceipt,
					sourceType: this.sourceType,
				}
				// 填充对方id
				this.fillTargetId(msgInfo, this.chat.targetId);
				this.sendMessageRequest(msgInfo).then((m) => {
					m.selfSend = true;
					this.chatStore.insertMessage(m);
					// 会话置顶
					this.moveChatToTop();
					// 滚动到底部
					this.scrollToBottom();
					this.isReceipt = false;
				})
			},
			onRtCall(msgInfo) {
				if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
					this.onPriviteVoice();
				} else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
					this.onPriviteVideo();
				}
			},
			onPriviteVideo() {
				const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
				uni.navigateTo({
					url: `/pageSubOne/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true&sourceType=${this.sourceType}`
				})
			},
			onPriviteVoice() {
				const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
				uni.navigateTo({
					url: `/pageSubOne/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true&sourceType=${this.sourceType}`
				})
			},
			onGroupVideo() {
				// 邀请成员发起通话
				let ids = [this.mine.id];
				this.$refs.selBox.init(ids, ids);
				this.$refs.selBox.open();
			},
			onInviteOk(ids) {
				if (ids.length < 2) {
					return;
				}
				let users = [];
				ids.forEach(id => {
					let m = this.groupMembers.find(m => m.userId == id);
					// 只取部分字段,压缩url长度
					users.push({
						id: m.userId,
						nickName: m.showNickName,
						headImage: m.headImage,
						isCamera: false,
						isMicroPhone: true
					})
				})
				const groupId = this.group.id;
				const inviterId = this.mine.id;
				const userInfos = encodeURIComponent(JSON.stringify(users));
				uni.navigateTo({
					url: `/pageSubOne/chat/chat-group-video?groupId=${groupId}&isHost=true
						&inviterId=${inviterId}&userInfos=${userInfos}&sourceType=${this.sourceType}`
				})
			},
			moveChatToTop() {
				this.chatStore.moveTop(this.chatIndex);
				this.chatIndex = this.chatStore.findChatIdx({
					id: this.chat.targetId,
					type: this.chat.type
				});
			},
			switchReceipt() {
				this.isReceipt = !this.isReceipt;
			},
			openAtBox() {
				this.$refs.atBox.init(this.atUserIds);
				this.$refs.atBox.open();
			},
			onAtComplete(atUserIds) {
				this.atUserIds = atUserIds;
			},
			onLongPressHead(msgInfo) {
				if (!msgInfo.selfSend && this.chat.type == "GROUP" && this.atUserIds.indexOf(msgInfo.sendId) < 0) {
					this.atUserIds.push(msgInfo.sendId);
				}
			},
			headImage(msgInfo) {
				if (this.chat.type == 'GROUP') {
					let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
					return member ? member.headImage : "";
				} else {
					return msgInfo.selfSend ? this.mine.headImageThumb : this.chat.headImage
				}
			},
			showName(msgInfo) {
				if (this.chat.type == 'GROUP') {
					let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
					return member && member.showNickName || "";
				} else {
					return msgInfo.selfSend && this.mine.nickName || this.chat.showName
				}
			},
			sendTextMessage() {

				if (!this.sendText.trim() && this.atUserIds.length == 0) {
					return
					/* return uni.showToast({
						title: "不能发送空白信息",
						icon: "none"
					}); */
				}
				this.containerHeight = 31
				let receiptText = this.isReceipt ? "【回执消息】" : "";
				let atText = this.createAtText();

				let msgInfo = {
					content: receiptText + this.sendText + atText,
					atUserIds: this.atUserIds,
					receipt: this.isReceipt,
					type: 0,
					sourceType: this.sourceType,
				}
				console.log(msgInfo);
				this.sendText = "";
				// 填充对方id
				this.fillTargetId(msgInfo, this.chat.targetId);
				this.sendMessageRequest(msgInfo).then((m) => {
					m.selfSend = true;
					this.chatStore.insertMessage(m);
					console.log("消息回调", m)
					const index = this.chatStore.findChatIdx({
						id: this.chat.targetId,
						type: this.chat.type
					});
					this.chatIndex = index
					this.chat = this.chatStore.chats[this.chatIndex]
					// 会话置顶
					this.moveChatToTop();
				}).finally(() => {
					// 滚动到底部
					this.scrollToBottom();
					// 清空@用户列表
					this.atUserIds = [];
					this.isReceipt = false;
					this.$refs.atBox.close();
				});
			},
			createAtText() {
				let atText = "";
				this.atUserIds.forEach((id) => {
					if (id == -1) {
						atText += ` @全体成员`;
					} else {
						let member = this.groupMembers.find((m) => m.userId == id);
						if (member) {
							atText += ` @${member.showNickName}`;
						}
					}
				})
				return atText;
			},
			fillTargetId(msgInfo, targetId) {
				if (this.chat.type == "GROUP") {
					msgInfo.groupId = targetId;
				} else {
					msgInfo.recvId = targetId;
				}
			},
			scrollToMsgIdx(idx) {
				console.log("scrollToMsgIdx", idx)
				// 如果scrollMsgIdx值没变化， 滚动条不会移动
				if (idx == this.scrollMsgIdx && idx > 0) {
					this.$nextTick(() => {
						// 先滚动到上一条
						this.scrollMsgIdx = idx - 1;
						// 再滚动目标位置
						this.scrollToMsgIdx(idx);
					});
					return;
				}
				this.$nextTick(() => {
					this.scrollMsgIdx = idx;
				});

			},
			onShowEmoChatTab() {
				console.log("测试")
				this.showRecord = false;
				this.switchChatTabBox('emo', true)
			},
			onShowToolsChatTab() {
				this.showRecord = false;
				this.switchChatTabBox('tools', true)
			},
			switchChatTabBox(chatTabBox, hideKeyBoard) {
				if (this.chatTabBox == chatTabBox) {
					this.chatTabBox = "none"
					this.scrollToBottom()
					return
				}
				this.chatTabBox = chatTabBox;
				if (hideKeyBoard) {
					uni.hideKeyboard();
					this.showKeyBoard = false;
				}
				this.scrollToBottom()
			},
			selectEmoji(emoText) {
				this.sendText += `${emoText}`;
			},
			onNavBack() {
				if (this.sourceType == 0) {
					uni.switchTab({
						url: "/pages/tabbar/chat"
					})
				} else if (this.sourceType == 1) {
					uni.switchTab({
						url: "/pages/tabbar/friend-business"
					})
				} else {
					uni.navigateBack()
				}
			},
			// onNavBack() {
			// 	uni.switchTab({
			// 		url: "/pageSubOne/chat/chat"
			// 	})
			// },
			onKeyboardheightchange(e) {
				if (e.detail.height > 0) {
					this.showKeyBoard = true;
					this.switchChatTabBox('none', false)
					// #ifdef MP-WEIXIN
					this.keyboardHeight = e.detail.height - 20;
					// this.containerHeight = this.keyboardHeight + this.containerHeight
					// #endif
					// #ifndef MP-WEIXIN
					this.keyboardHeight = this.rpxTopx(e.detail.height);
					// #endif
					// this.keyboardHeight = e.detail.height;
				} else {
					this.keyboardHeight = 0
					this.showKeyBoard = false;
				}
				this.scrollToBottom();
			},
			onUploadImageBefore(file) {
				let data = {
					originUrl: file.path,
					thumbUrl: file.path
				}
				let msgInfo = {
					id: 0,
					tmpId: this.generateId(),
					fileId: file.uid,
					sendId: this.mine.id,
					content: JSON.stringify(data),
					sendTime: new Date().getTime(),
					selfSend: true,
					type: this.$enums.MESSAGE_TYPE.IMAGE,
					readedCount: 0,
					loadStatus: "loading",
					status: this.$enums.MESSAGE_STATUS.UNSEND
				}
				// 填充对方id
				this.fillTargetId(msgInfo, this.chat.targetId);
				// 插入消息
				this.chatStore.insertMessage(msgInfo);
				// 会话置顶
				this.moveChatToTop();
				// 借助file对象保存
				file.msgInfo = msgInfo;
				// 滚到最低部
				this.scrollToBottom();
				return true;
			},

			onUploadImageSuccess(file, res) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				msgInfo.content = JSON.stringify(res.data);
				msgInfo.receipt = this.isReceipt
				msgInfo.sourceType = this.sourceType
				this.sendMessageRequest(msgInfo).then((m) => {
					msgInfo.loadStatus = 'ok';
					msgInfo.id = m.id;
					this.isReceipt = false;
					this.chatStore.insertMessage(msgInfo);
				})
			},
			onUploadImageFail(file, err) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				msgInfo.loadStatus = 'fail';
				this.chatStore.insertMessage(msgInfo);
			},
			onUploadFileBefore(file) {
				let data = {
					name: file.name,
					size: file.size,
					url: file.path
				}
				let msgInfo = {
					id: 0,
					tmpId: this.generateId(),
					sendId: this.mine.id,
					content: JSON.stringify(data),
					sendTime: new Date().getTime(),
					selfSend: true,
					type: this.$enums.MESSAGE_TYPE.FILE,
					readedCount: 0,
					loadStatus: "loading",
					status: this.$enums.MESSAGE_STATUS.UNSEND
				}
				// 填充对方id
				this.fillTargetId(msgInfo, this.chat.targetId);
				// 插入消息
				this.chatStore.insertMessage(msgInfo);
				// 会话置顶
				this.moveChatToTop();
				// 借助file对象保存
				file.msgInfo = msgInfo;
				// 滚到最低部
				this.scrollToBottom();
				return true;
			},
			onUploadFileSuccess(file, res) {
				let data = {
					name: file.name,
					size: file.size,
					url: res.data
				}
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				msgInfo.content = JSON.stringify(data);
				msgInfo.receipt = this.isReceipt
				msgInfo.sourceType = this.sourceType
				this.sendMessageRequest(msgInfo).then((m) => {
					msgInfo.loadStatus = 'ok';
					msgInfo.id = m.id;
					this.isReceipt = false;
					this.chatStore.insertMessage(msgInfo);
				})
			},
			onUploadFileFail(file, res) {
				let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
				msgInfo.loadStatus = 'fail';
				this.chatStore.insertMessage(msgInfo);
			},
			onDeleteMessage(msgInfo) {
				uni.showModal({
					title: '删除消息',
					content: '确认删除消息?',
					success: (res) => {
						if (!res.cancel) {
							this.chatStore.deleteMessage(msgInfo);
							uni.showToast({
								title: "删除成功",
								icon: "none"
							})
						}
					}
				})
			},
			onRecallMessage(msgInfo) {
				uni.showModal({
					title: '撤回消息',
					content: '确认撤回消息?',
					success: (res) => {
						if (!res.cancel) {
							let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
							this.$http({
								url: url,
								method: 'DELETE'
							}).then(() => {
								msgInfo = JSON.parse(JSON.stringify(msgInfo));
								msgInfo.type = this.$enums.MESSAGE_TYPE.RECALL;
								msgInfo.content = '你撤回了一条消息';
								msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
								this.chatStore.insertMessage(msgInfo);
							})
						}
					}
				})
			},
			onFavorite(msgInfo) {
				this.$http({
					url: "/favorite",
					method: "POST",
					data: {
						targetId: msgInfo.sendId,
						content: msgInfo.content,
						type: msgInfo.type,
						msgId: msgInfo.id,
						msgType: msgInfo.groupId && 1 || 0
					}
				}).then(res => {
					uni.showToast({
						icon: 'none',
						title: "收藏成功"
					})
				})
			},
			onCopyMessage(msgInfo) {
				uni.setClipboardData({
					data: msgInfo.content,
					success: () => {
						uni.showToast({
							title: '已复制',
							icon: 'none'
						});
					},
					fail: () => {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						});
					}
				});
			},
			onDownloadFile(msgInfo) {
				let url = JSON.parse(msgInfo.content).url;
				uni.downloadFile({
					url: url,
					success(res) {
						if (res.statusCode === 200) {
							var filePath = encodeURI(res.tempFilePath);
							uni.openDocument({
								filePath: filePath,
								showMenu: true
							});
						}
					},
					fail(e) {
						uni.showToast({
							title: "文件下载失败",
							icon: "none"
						})
					}
				});
			},
			onScrollToTop() {
				if (this.showMinIdx == 0) {
					console.log("消息已滚动到顶部")
					return;
				}
				//  #ifndef H5
				// 防止滚动条定格在顶部，不能一直往上滚
				this.scrollToMsgIdx(this.showMinIdx);
				// #endif
				// 多展示0条信息
				this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
			},
			onShowMore() {
				let chatIdx = this.chatStore.findChatIdx(this.chat);
				if (this.chat.type == "GROUP") {
					uni.navigateTo({
						url: `/pageSubOne/group/group-info?id=${this.group.id}&chatIdx=${chatIdx}&sourceType=${this.sourceType}&fromThis=false`
					})
				} else {
					uni.navigateTo({
						url: `/pageSubOne/common/user-info?id=${this.friend.id}&chatIdx=${chatIdx}&sourceType=${this.sourceType}&friendType=${this.sourceType}&fromThis=true`
					})
				}
			},
			onTextInput(e) {
				let idx = e.detail.cursor - 1;
				if (this.chat.type == 'GROUP' && e.detail.value[idx] == '@') {
					this.openAtBox();
					let sendText = e.detail.value.replace("@", '');
					this.$nextTick(() => {
						this.sendText = sendText;
					})
				}
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this)
					query.select('.send-text-area').boundingClientRect(res => {
						console.log(res.height)
						this.containerHeight = res.height
					}).exec()
				})
			},
			loadReaded(fid) {
				const that = this
				this.$http({
					url: `/message/private/maxReadedId?friendId=${fid}`,
					method: 'get'
				}).then((id) => {
					this.chatStore.readedMessage({
						friendId: fid,
						maxId: id,
						type: that.sourceType,
					});
				});
			},
			readedMessage() {
				if (this.unreadCount == 0) {
					return;
				}
				let url = ""
				if (this.chat.type == "GROUP") {
					url = `/message/group/readed?groupId=${this.chat.targetId}`
				} else {
					url = `/message/private/readed?friendId=${this.chat.targetId}`
				}
				this.$http({
					url: url,
					method: 'PUT'
				}).then(() => {
					this.chatStore.resetUnreadCount(this.chat)
					this.scrollToBottom();
				})
			},
			loadGroup(groupId) {
				this.$http({
					url: `/group/checkIsUserInGroup`,
					method: 'POST',
					data: [{
						"groupId": groupId
					}]
				}).then(res => {
					this.inGroup = res[0].inGroup
				})

				this.$http({
					url: `/group/find/${groupId}`,
					method: 'GET'
				}).then((group) => {
					this.group = group;
					this.chatStore.updateChatFromGroup(group);
					this.groupStore.updateGroup(group);
				});


				this.$http({
					url: `/group/members/${groupId}`,
					method: 'GET'
				}).then((groupMembers) => {
					this.groupMembers = groupMembers;
				});
			},
			loadFriend(friendId) {
				console.log("friendId", friendId)
				// 获取对方最新信息
				this.$http({
					url: `/friend/find/${friendId}`,
					method: 'GET'
				}).then((friend) => {
					this.friend = friend.user;
					console.log("friend.user", friend)
					this.chatStore.updateChatFromFriend(friend);
					console.log("测试", friend)
					this.friendStore.updateFriend(friend);
				})
			},
			// 获取工作号最新信息
			loadWorkFriend(friendId) {
				console.log("friendId", friendId)
				// 获取对方最新信息
				this.$http({
					url: `/work/friend/find/${friendId}`,
					method: 'GET'
				}).then((friend) => {
					this.friend = friend.user;
					console.log("friend.user", friend)
					this.chatStore.updateChatFromFriend(friend);
					console.log("测试", friend)
					this.friendStore.updateFriend(friend);
				})
			},
			rpxTopx(rpx) {
				// px转换成rpx
				let info = uni.getSystemInfoSync()
				let px = info.windowWidth * rpx / 750;
				return Math.floor(rpx);
			},
			sendMessageRequest(msgInfo) {
				return new Promise((resolve, reject) => {
					// 请求入队列，防止请求"后发先至"，导致消息错序
					this.reqQueue.push({
						msgInfo,
						resolve,
						reject
					});
					this.processReqQueue();
				})
			},
			processReqQueue() {
				if (this.reqQueue.length && !this.isSending) {
					this.isSending = true;
					const reqData = this.reqQueue.shift();
					this.$http({
						url: this.messageAction,
						method: 'post',
						data: reqData.msgInfo
					}).then((res) => {
						reqData.resolve(res)
					}).catch((e) => {
						reqData.reject(e)
					}).finally(() => {
						this.isSending = false;
						// 发送下一条请求
						this.processReqQueue();
					})
				}
			},
			listenKeyBoardForH5() {
				// 由于H5无法触发TextArea的@keyboardheightchange事件，所以通过
				// 监听屏幕高度变化来实现键盘监听
				let initHeight = window.innerHeight;
				window.addEventListener('resize', () => {
					let keyboardHeight = initHeight - window.innerHeight;
					if (keyboardHeight > 0) {
						this.keyboardHeight = keyboardHeight - 20;
						this.showKeyBoard = true;
						this.switchChatTabBox('none', false)
						this.scrollToBottom();
					} else {
						this.showKeyBoard = false;
					}
				});
			},
			generateId() {
				// 生成临时id
				return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
			}
		},
		computed: {
			funcMap() {
				return this.enableStore.funcMap
			},
			messageList() {
				console.log("this.type", this.type)
				// 群聊消息
				if (this.type == 'GROUP') {
					return this.chat.messages
				}
				// 私聊消息
				else if (this.type == 'PRIVATE') {
					// 普通私聊
					if (this.sourceType == 0) {
						const chats = this.chatStore.privateChats.filter(e => e.targetId == this.id)
						return chats && chats[0] && chats[0].messages
					}
					// 友商私聊

					// 工作号私聊
					else if (this.sourceType == 2) {
						const chats = this.chatStore.workPrivateChats.filter(e => e.targetId == this.id)
						return chats && chats[0] && chats[0].messages
					}
				} else if (this.type == 'BUSINESS') {
					// 工作号私聊
					const chats = this.chatStore.businessPrivateChats.filter(e => e.targetId == this.id)
					return chats && chats[0] && chats[0].messages

				}


			},
			mine() {
				return this.userStore.userInfo;
			},
			title() {
				if (!this.chat) {
					return "";
				}
				let title = this.chat.showName;
				console.log("title", this.chat)
				if (this.chat.type == "GROUP") {
					let size = this.groupMembers.filter(m => !m.quit).length;
					title += `(${size})`;
				}
				return title;
			},
			messageAction() {
				if (this.chat.type.toLowerCase() === 'group') {
					return `/message/${this.chat.type.toLowerCase()}/send`;
				}

				return `/message/private/send`;
			},
			messageSize() {
				if (!this.chat || !this.messageList) {
					return 0;
				}
				return this.messageList.length;
			},
			unreadCount() {
				if (!this.chat || !this.chat.unreadCount) {
					return 0;
				}
				return this.chat.unreadCount;
			},
			atUserItems() {
				let atUsers = [];
				this.atUserIds.forEach((id) => {
					if (id == -1) {
						atUsers.push({
							id: -1,
							showNickName: "全体成员"
						})
						return;
					}
					let member = this.groupMembers.find((m) => m.userId == id);
					if (member) {
						atUsers.push(member);
					}
				})
				return atUsers;
			},
			
		},
		watch: {
			messageSize: function(newSize, oldSize) {
				// 接收到消息时滚动到底部
				if (newSize > oldSize) {
					let pages = getCurrentPages();
					let curPage = pages[pages.length - 1].route;
					if (curPage == "pageSubOne/chat/chat-box") {
						this.scrollToBottom();
					} else {
						this.needScrollToBottom = true;
					}
				}
			},
			unreadCount: {
				handler(newCount, oldCount) {
					if (newCount > 0) {
						// 消息已读
						this.readedMessage()
					}
				}
			},
			keyboardHeight: {
				handler(newCount, oldCount) {
					const self = this
					setTimeout(() => {
						self.scrollToBottom()
					}, 100)
				}
			}
		},
		onUnload() {
			// #ifndef H5
			uni.offKeyboardHeightChange(this.onKeyboardheightchange);
			// #endif
		},
		onLoad(options) {
			// id 除了用户id 还有可能是工作号id
			this.id = options.id
			console.log("chat-boxoptions", options)

			// 工作号相关参数
			// 工作号id
			const userId = options.userId
			const userType = options.type
			const sourceType = options.sourceType



			// #ifdef H5
			let initialHeight = window.innerHeight;
			window.addEventListener('resize', () => {
				let currentHeight = window.innerHeight;
				this.scrollViewHeight = this.scrollViewHeight + ((initialHeight - currentHeight) == 0 ? +this
						.keyboardHeight : -(initialHeight - currentHeight)) - (this.fixNotice.length > 0 ? 24 :
						0) -
					// 工具bar
					(this.chatTabBox == "none" ? 50 : 300)
				// this.keyboardHeight = initialHeight - currentHeight;
				this.scrollToBottom()
			});
			// #endif
			// #ifndef H5
			uni.onKeyboardHeightChange(this.onKeyboardheightchange)
			// #endif
			// 来源$enums.privateMessageType
			// 来源必填
			const self = this
			if (isNullOrEmpty(options.sourceType)) {
				uni.showToast({
					title: "来源错误",
					icon: "none",
					duration: 500,
					complete() {
						setTimeout(self.goBack, 500)
					}
				})
				return
			}
			this.sourceType = parseInt(options.sourceType)
			this.type = options.type
			// #ifdef H5
			this.isH5 = true;
			this.listenKeyBoardForH5();
			// #endif
			// 聊天数据
			const index = this.chatStore.findChatIdx({
				id: options.id,
				type: options.type
			});
			this.chatIndex = index
			this.chat = this.chatStore.curChats[index]
			// 初始状态只显示20条消息
			let size = this.messageSize;
			this.showMinIdx = size > 20 ? size - 20 : 0;
			// 消息已读
			this.readedMessage()
			// 加载好友或群聊信息
			if (this.chat.type == "GROUP") {
				this.loadGroup(this.chat.targetId);
				this.loadGroupNotice(this.chat.targetId) //加载最新公告
			} else {
				// 获取用户信息
				if (this.sourceType == 0 || this.sourceType == 1) {
					this.loadFriend(this.chat.targetId);
					this.loadReaded(this.chat.targetId)
				} else {
					this.loadWorkFriend(this.chat.targetId)
					console.log("工作号", this.sourceType)
				}

			}
			// 激活当前会话
			this.chatStore.activeChat(this.chatIndex);
			// 复位回执消息
			this.isReceipt = false;
			// 挪到顶上
			this.moveChatToTop();
		},
		onShow() {
			if (this.needScrollToBottom) {
				// 页面滚到底部
				this.scrollToBottom();
				this.needScrollToBottom = false;
			}


		}
	}
</script>

<style lang="scss" scoped>
	.chat-box {
		position: relative;
		border: #dddddd solid 1px;
		display: flex;
		flex-direction: column;

		.top_daohang {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-evenly;

		}

		.top_daohang_font {
			width: 70px;
			text-align: center;
			margin-top: -10rpx;
			border-radius: 4px;
			color: #F04438;
			background-color: #D3C5A5;
		}

		.notice {
			position: fixed;
			top: 90rpx;
			left: 0;
			width: 100%;
			z-index: 100;
		}

		.red-dot {
			width: 20rpx;
			height: 20rpx;
			background-color: $error-500;
			border-radius: 50%;
			position: absolute;
			right: 10rpx;
			top: 0;
		}

		.fixNotice {
			position: relative;
			height: 36rpx;
			line-height: 36rpx;
			display: inline-block;
			white-space: nowrap;
			border-radius: 34rpx;
			padding: 8rpx 24rpx;
			border: 1rpx solid $success-500;
			background-color: $success-100;
			color: $success-500;
			text-overflow: ellipsis;
			overflow: hidden;
			max-width: 140rpx;
			font-size: 26rpx;
			// margin: 0 20rpx;
			gap: 16rpx;
		}

		.fixNotice1 {
			position: relative;
			height: 36rpx;
			line-height: 36rpx;
			display: inline-block;
			white-space: nowrap;
			border-radius: 34rpx;
			padding: 8rpx 24rpx;
			border: 1rpx solid $gray-500;
			background-color: $gray-100;
			color: $gray-500;
			text-overflow: ellipsis;
			overflow: hidden;
			max-width: 140rpx;
			font-size: 26rpx;
			// margin: 0 20rpx;
			gap: 16rpx;
		}

		.chat-msg {
			flex: 1;
			padding: 0;
			// overflow: hidden;
			position: relative;
			background-color: #F5F5F5;

			// .container{
			// 	width: 100%;
			// 	height: 100%;
			// 	position: absolute;
			// 	top: 0;
			// 	right: 0;
			.movable-area {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;

				.movable-view {
					// position: absolute;
					// top: 0;
					// right: 0;
					// left: 62vw;
					width: 140px;
					height: 190px;
					z-index: 299;

					.video-element {
						// position: absolute;
						// top: 0;
						// right: 0;
						width: 100%;
						height: 100%;
						object-fit: cover;
						z-index: 200;
					}
				}
			}




			// }



			.scroll-box {
				height: 100%;
			}
		}

		.chat-at-bar {
			display: flex;
			align-items: center;
			padding: 0 10rpx;

			.icon-at {
				font-size: 35rpx;
				color: darkblue;
				font-weight: 600;
			}

			.chat-at-scroll-box {
				flex: 1;
				width: 80%;

				.chat-at-items {
					display: flex;
					align-items: center;
					height: 70rpx;
					background-color: transparent;

					.chat-at-item {
						padding: 0 3rpx;
					}
				}
			}

		}

		.send-panel {
			position: fixed;
			bottom: 0;
			width: 100%;
			box-sizing: border-box;
			background-color: #FFFFFF;

			.fixed-notice {
				display: flex;
				flex-wrap: wrap;
				padding: 16rpx 32rpx;
				gap: 16rpx;
			}

			.send-bar {
				border-top: 1px solid $gray-200;
				display: flex;
				align-items: center;
				padding: 20rpx;
				height: 82rpx;
				gap: 16rpx;

				.iconfont {
					font-size: 50rpx;
					margin: 10rpx;
				}

				.chat-record {
					flex: 1;

				}

				.send-text.disabled {
					background-color: #f4f4f5;
					display: flex;
					align-items: center;
				}

				.send-text {
					flex: 1;
					overflow: auto;
					padding: 16rpx;
					border-radius: 30rpx;
					font-size: 30rpx;
					box-sizing: border-box;
					border: 1rpx solid #F9F9F9;
					position: relative;
					background-color: $gray-100;

					.not-in-group {
						position: absolute;
						font-size: 22rpx;
						color: #82848a;
						width: 100%;
						text-align: center;
					}

					.send-text-area {
						// 固定高度
						height: 36rpx;
						width: 100%;
					}

				}

				.btn-send {
					background-color: $brand-500;
					margin: 5rpx;
				}
			}

			.chat-tab-bar {
				height: 500rpx;
				padding: 20rpx;
				background-color: #f8f8f8;

				.chat-tools {
					display: grid;
					grid-template-columns: repeat(auto-fill, 160rpx);
					grid-gap: 20rpx 20rpx;
					justify-content: space-between;

					.chat-tools-item {
						padding: 16rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 20rpx;

						.tool-icon {
							padding: 28rpx;
							font-size: 60rpx;
							border-radius: 20%;
							background-color: white;
							color: black;

							&.active {
								background-color: #ddd;
							}
						}

						.tool-icons {
							padding: 16rpx;
							background-color: $warning-50;
							border-radius: 16rpx;
							height: 60rpx;
						}

						.tool-icons1 {
							padding: 16rpx;
							background-color: $brand-50;
							border-radius: 16rpx;
							height: 60rpx;
						}

						.tool-icons2 {
							padding: 16rpx;
							background-color: $warning-50;
							border-radius: 16rpx;
							height: 52rpx;
						}

						.tool-icons3 {
							padding: 16rpx;
							background-color: $success-50;
							border-radius: 16rpx;
							height: 60rpx;
						}

						.tool-name {
							height: 60rpx;
							line-height: 60rpx;
							font-size: 28rpx;
						}
					}
				}

				.chat-emotion {
					height: 100%;

					.emotion-item-list {
						display: grid;
						grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;

						.emotion-item {
							font-size: 50rpx;
							text-align: center;
							cursor: pointer;
						}
					}
				}

			}
		}
	}
</style>